<template>
  <div class="app-container">
    <el-dialog :title="id ? '修改' : '新增'" :visible.sync="visible" width="800px" :before-close="handleClose"
      append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item v-if="!buildingId" label="楼幢" prop="chosebuildingId">
          <el-select v-model="form.chosebuildingId" placeholder="请选择楼幢" clearable size="small"
            :disabled="id ? true : false">
            <el-option v-for="dict in buildingList" :key="dict.buildingId" :label="dict.buildingName"
              :value="dict.buildingId" />
          </el-select>
        </el-form-item>
        <el-form-item label="序列号" prop="sort">
          <el-input v-model="form.sort" />
        </el-form-item>
        <el-form-item label="楼层编号" prop="mapNo">
          <el-input v-model="form.mapNo" :disabled="id ? true : false" />
        </el-form-item>
        <el-form-item label="楼层名称" prop="mapName">
          <el-input v-model="form.mapName" />
        </el-form-item>
        <el-form-item label="楼层平面" prop="file">
          <FileUpload v-model="form.file" :fileType="['png', 'jpg', 'jpeg']" :url="url" @input="getFirelist"
            @deleteFile="deleteFile" @giveMediaType="giveMediaType" @getImageDimensions="getImageDimensions"
            ref="fileUpload" :dynamicHeaders="dynamicHeaders" :dynamicMethod="dynamicMethod" :dynamicUrl="dynamicUrl"
            :ossId="ossId" :limit="1" :listType="'picture'" :who="'file'" :drag="true"></FileUpload>
        </el-form-item>
        <el-form-item label="楼层建模" prop="model">
          <FileUpload v-model="form.model" :fileType="['glb']" :url="url" @input="getFirelist" @deleteFile="deleteFile"
            @giveMediaType="giveMediaType" @getImageDimensions="getImageDimensions" ref="fileUpload2"
            :dynamicHeaders="dynamicHeaders" :dynamicMethod="dynamicMethod" :dynamicUrl="dynamicUrl" :ossId="ossId"
            :limit="1" :listType="'text'" :who="'model'" :drag="true"></FileUpload>
        </el-form-item>
        <el-form-item label="楼层描述" prop="description">
          <editorCom ref="editorCom" :value="form.description" @input="handleInput"></editorCom>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancle">取 消</el-button>
        <el-button type="primary" @click="sub">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import FileUpload from "@/components/FileUpload";
import editorCom from "@/components/Editor";
import { postOssUpload } from "@/api/oss";
import { addFloor, editFloor, getbuildingArr } from "@/api/map";
import { onlyNumberRules, specialRules } from "@/utils/rules";
export default {
  name: "Add",
  components: {
    FileUpload,
    editorCom,
  },
  props: {
    id: {
      type: [Number, String],
      default: "",
    },
    visible: {
      type: Boolean,
      default: false,
    },
    objTarget: {
      type: String,
      default: "",
    },
    buildingId: {
      type: [Number, String],
      default: "",
    },
  },
  data() {
    // 定义校验规则
    const validatemapNo = (rule, value, callback) => {
      if (!value) {
        callback(new Error("楼层编号不能为空"));
      } else if (!onlyNumberRules.test(value)) {
        callback(new Error("楼层编号只能为数字"));
      } else {
        callback();
      }
    };
    const validatesort = (rule, value, callback) => {
      if (!value) {
        callback(new Error("序列号不能为空"));
      } else if (!onlyNumberRules.test(value)) {
        callback(new Error("序列号只能为数字"));
      } else {
        callback();
      }
    };
    const validatemapName = (rule, value, callback) => {
      if (!value) {
        callback(new Error("楼层名称不能为空"));
      } else if (!specialRules.test(value)) {
        callback(new Error("请输入合法的楼层名称"));
      } else {
        callback();
      }
    };
    return {
      form: {
        // chosebuildingId: "",// 当不是子页面跳转的时候，需要下拉选择buildingId
      },
      uploadParams: {
        path: "map-floor",
        name: "",
        permission: "tenant",
        suffix: "",
        mediaType: "",
        sizeLimit: "",
        attachment: "",
      },
      rules: {
        chosebuildingId: [
          { required: true, message: "请选择楼幢", trigger: "change" },
        ],
        sort: [{ required: true, validator: validatesort, trigger: "blur" }],
        mapNo: [{ required: true, validator: validatemapNo, trigger: "blur" }],
        mapName: [
          { required: true, validator: validatemapName, trigger: "blur" },
        ],
        file: [],
        model: [],
        description: [],
      },
      url: "",
      ossId: "",
      dynamicHeaders: {},
      dynamicMethod: "PUT",
      dynamicUrl: null,
      imageOidList: [],
      modelOidList: [],
      w: 0,
      h: 0,
      buildingList: [],
    };
  },
  watch: {
    id: {
      handler(val) {
        if (val) {
          this.giveDetail();
        }
      },
      deep: false,
      immediate: false,
    },
    visible: {
      handler(val) {
        if (val) {
          if (!this.buildingId) {
            this.requestgetbuildingArr();
          }
        }
      },
      deep: false,
      immediate: false,
    },
  },
  methods: {
    requestgetbuildingArr() {
      getbuildingArr()
        .then((res) => {
          if (res.success) {
            this.buildingList = res?.data ?? [];
          }
        })
        .catch((err) => { });
    },
    handleInput(val) {
      this.form.description = val;
    },
    giveDetail() {
      let objTarget = JSON.parse(this.objTarget);
      console.log(objTarget);
      this.form = {
        sort: objTarget.sort,
        mapNo: objTarget.mapNo,
        mapName: objTarget.mapName,
        description: objTarget.description,
        file: objTarget.imageUrlList,
        model: [objTarget?.groundModelName ?? "未知模型名称"],
      };
      if (objTarget.buildingId) {
        this.$set(this.form, "chosebuildingId", objTarget.buildingId);
      }
      this.imageOidList = objTarget.imageOidList;
      this.modelOidList = [objTarget.groundModelOid];
    },
    giveMediaType(mediaType, who) {
      this.uploadParams.mediaType = mediaType;
      if (who === 'file') {
        this.uploadParams.suffix = this.uploadParams.mediaType.match(/\/(.+)/)[1]
      } else {
        this.uploadParams.suffix = 'glb'
      }
      this.requestpostOssUpload(who);
    },
    requestpostOssUpload(who) {
      if (who === "file") {
        this.uploadParams.name = "楼层图片";
        // this.uploadParams.suffix = "jpg";
      } else {
        this.uploadParams.name = "楼层建模";
        // this.uploadParams.suffix = "glb";
      }
      postOssUpload(this.uploadParams)
        .then((res) => {
          if (res.success) {
            this.dynamicHeaders = res.data.headers || {};
            this.dynamicMethod = res.data.method || "PUT";
            this.dynamicUrl = res.data.uploadUrl || "";
            this.ossId = res?.data?.ossId ?? null;
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
    getFirelist(data, who) {
      console.log(data, "data");
      let arr;
      data.forEach((item) => {
        if (who === "file") {
          arr = this.imageOidList;
        } else {
          arr = this.modelOidList;
        }
        // 不包含该ossId则push
        if (item.ossId && !arr.includes(item.ossId)) {
          arr.push(item.ossId);
        }
      });
      this.dynamicHeaders = {};
      this.dynamicMethod = "PUT";
      this.dynamicUrl = null;
      this.ossId = "";
    },
    deleteFile(file, who) {
      let flage, arr;
      if (who === "file") {
        flage = this.form.file;
        arr = this.imageOidList;
      } else {
        flage = this.form.model;
        arr = this.modelOidList;
      }
      // 找到form.file中对应的对象，删除
      let index = flage.findIndex((item) => {
        if (typeof item === "object" && Object.keys(item).length > 0) {
          return item.url === file.url;
        } else {
          return item === file.url;
        }
      });
      if (index !== -1) {
        // 找到imageOidList中对应的对象，删除
        flage.splice(index, 1);
        arr.splice(index, 1);
      }
    },
    cancle() {
      this.handleClose(false);
    },
    getImageDimensions(data) {
      this.w = data.width;
      this.h = data.height;
    },
    sub() {
      // 触发表单校验
      this.$refs.form.validate((valid) => {
        if (valid) {
          // 校验通过，执行提交逻辑
          let requestWay, msg, errmsg;
          let queryParams = {
            sort: this.form.sort,
            mapNo: this.form.mapNo,
            mapName: this.form.mapName,
            description: this.form.description,
            imageOidList: this.imageOidList,
            buildingId: this.buildingId
              ? this.buildingId
              : this.form.chosebuildingId,
            groundOid: this.imageOidList[0], // 楼层平面OSSID
            groundModelOid: this.modelOidList[0], // 楼层建模OSSID
            w: this.w,
            h: this.h,
          };
          if (this.id) {
            requestWay = editFloor;
            queryParams.mapId = this.id;
            msg = "修改成功";
            errmsg = "修改失败";
          } else {
            requestWay = addFloor;
            msg = "新增成功";
            errmsg = "新增失败";
          }
          console.log("提交表单数据:", queryParams);
          requestWay(queryParams)
            .then((res) => {
              if (res.success) {
                this.$message.success(msg);
                this.handleClose(true);
              } else {
                this.$message.error(errmsg);
              }
            })
            .catch((err) => {
              console.log(err);
            });
        } else {
          console.log("表单校验未通过");
          return false;
        }
      });
    },
    handleClose(status) {
      this.form = {};
      this.imageOidList = [];
      // 重置表单
      this.$refs.form.resetFields();
      this.$emit("update:visible", false);
      this.$emit("close", status === true ? status : false);
    },
  },
};
</script>

<style scoped></style>
